<?php

namespace app\admin\middleware;

use app\admin\model\CategoryAdmin;
use app\admin\validate\Article as ValidateArticle;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Session;

class Article
{
    public function handle($request, \Closure $next)
    {
        $param = input();
        $action = $request->action();
        try {
            validate(ValidateArticle::class)->scene('add')->check($param);
            // 判断是否存在分类
            $cate = Db::name('category')->where(['id' => $param['cate_id'], 'status' => 1])->find();
            if (!$cate) return error('分类不存在');

            if ($param['type'] != 1 && empty($param['hide_content'])) {
                return error('隐藏内容不能为空', 201);
            }
            if ($param['type'] == 2 && @$param['score'] == '') {
                return error('付费文章积分不能为空', 201);
            }
            if ($param['type'] == 2 && $param['score'] <= 0) {
                return error('付费文章积分不能小于0');
            }
            $admin = Session::get('admin');
            $cateId = CategoryAdmin::getChildCateId($admin['id']);
            if (($admin['role'] == 2 && in_array($param['cate_id'], $cateId)) || $admin['role'] == 0) {
                $status = 1;
            } else {
                $status = 0;
            }
            $data = [
                'title' => $param['title'],
                'cate_id' => $param['cate_id'],
                'content' => $param['content'],
                'status' => $status,
                'type' => $param['type'],
                'score' => $param['type'] == 2 ? @$param['score'] : 0,
                'hide_content' => @$param['hide_content'],
                'images' => @$param['images'],
                'is_top' => @$param['is_top'] ?? 0,
                'is_hot' => @$param['is_hot']  ?? 0
            ];
            $request->param = $data;
        } catch (ValidateException $e) {
            return error($e->getError(), 201);
        }

        return $next($request);
    }
}
